<template>
    <div style="width: 95%;margin: auto;">
        <el-form :inline="true" :model="newsForm" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="newsForm.title" placeholder="请输入新闻标题" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="newsForm.content" placeholder="请输入新闻内容" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="newsForm.username" placeholder="请输入作者名字" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-button type="primary" @click="findAll(1)">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 新增和修改按钮 -->
    <div style="width: 95%;margin: auto;">
        <el-button type="primary" @click="showDialog()" :icon="Plus"> 新增</el-button>
        <el-button type="primary" @click="batchedDeleteByIds()" :icon="Delete"> 批量删除</el-button>
    </div>
    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable :show-close="false"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <!-- 新增用户表单 -->
            <el-form :inline="true" :model="dialog.news" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialog.news.title" placeholder="请输入新闻标题" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>
                <el-input v-model="dialog.news.content" :rows="2" placeholder="输入新闻内容"
                    style="width: 340px;margin-top: 20px;" />
                <el-form-item style="margin-top: 20px;">
                    <el-button type="primary" @click="insertAndUpdateUser">{{ dialog.btnText }}</el-button>
                    <el-button type="primary" @click="clearFormData">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

    <!-- 所有用户信息展示 -->
    <el-table :data="newsPage.news" style="width: 95% ; margin:auto" @selection-change="handleSelectionChange">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="newsid" label="编号" width="80" />
        <el-table-column prop="title" label="标题" width="250" />
        <el-table-column prop="content" label="内容" width="300" />
        <el-table-column prop="createtime" label="创建时间" width="300" :formatter="formatDateTime" />
        <el-table-column prop="username" label="作者" width="100" />
        <el-table-column label="操作" min-width="160" fixed="right">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
                    修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页标签 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="newsForm.pageSize"
            v-model:current-page="newsForm.pageNum" :total="newsForm.total" @current-change="findAll" />
    </div>
</template>
<script lang="ts" setup>

import { ref, reactive, onMounted } from 'vue'
import { Delete, Edit, Female, Male, HomeFilled, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useUserStore } from '@/stores/userStore'
//创建stote实例
let store = useUserStore();
const username = store.userinfo.username;
const newsPage = reactive({
    news: [],//存放后端查询用户数据变量
})

//声明一个对象用于条件查询
let newsForm = ref({
    pageNum: 0,
    pageSize: 8,
    total: 0,
})
//根据条件查询信息
const findAll = async (currentpage) => {
    newsForm.value.pageNum = currentpage;
    let res = await request.post("/news/queryCondition", newsForm.value);
    if (res.data.success) {
        newsPage.news = res.data.data.list;
        newsForm.value.pageNum = res.data.data.pageNum;
        newsForm.value.pageSize = res.data.data.pageSize;
        newsForm.value.total = res.data.data.total;
    }
}

const formatDateTime = (row, column) => {
    const date = new Date(row.createtime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
    findAll(1);
});
//定义对话框属性
const dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    news: {},
})
// 根据姓名查询uid
const selectByUsername = async () => {
    let res = await request.get(`/user/findIdByName/${username}`);
    if (res.data.success) {
        dialog.value.news.uid = res.data.data;
    }
}
//实现用户新增或者修改操作
const insertAndUpdateUser = async () => {
    if (dialog.value.btnText == "新增") {
        //查看是否有值
        //发送请求实现熊增用户功能
        // 等待uid查询完成后再进行后续操作
        const uid = await selectByUsername();
        // 检查uid是否获取成功
        if (uid === null) {
            ElMessage.error("获取用户ID失败,请检查用户名");
            return;
        }
        selectByUsername();
        console.log(dialog.value.news);

        let res = await request.post("/news/insert", dialog.value.news);
        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(1);
            //3.显示提示信息
            ElMessage.success("添加成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    } else {//表示修改
        //1.获取数据发送请求实现修改用户信息
        let res = await request.put("/news/update", dialog.value.news);

        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(newsForm.value.pageNum);//查询当前页
            //3.显示提示信息
            ElMessage.success("修改成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    }
}

//显示修改用户对话框
const handleEdit = (index, row) => {
    //显示表单信息
    dialog.value.news = row;
    //设置对话框标题
    dialog.value.title = "修改新闻";
    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
}

//显示新增对话框
const showDialog = () => {
    //1.设置对话框标题
    dialog.value.title = "新增新闻";
    //2.设置对话框 案例文本
    dialog.value.btnText = "新增";
    //3.清空表单
    clearFormObj();
    //4.显示对话框
    dialog.value.visible = true;
}

//选中文件时触发函数
const handlerImage = (file) => {
    uploadDialog.uploadFile = file.raw;
}
const clearFormData = () => {
    dialog.value.visible = false; // 关闭对话框
    findAll(newsForm.value.pageNum);
}
// 重置查询条件
const resetForm = () => {
    newsForm.value.title = "";
    newsForm.value.content = "";
    newsForm.value.username = null;
}
//清空表单函数
const clearFormObj = () => {
    dialog.value.news.title = '';
    dialog.value.news.content = '';
    dialog.value.news.createtime = null;
    dialog.value.news.uid = null;
}

//删除行操作
const handleDelete = async (row) => {
    let res = await request.delete(`/news/deleteById/${row.newsid}`, { params: row });
    if (res.data.success) {
        ElMessage.success("删除成功");
        findAll(1);
    }
}
// 批量删除
//定义数组，存放批量删除元素集合
const news = reactive({
    usersIds: [],
})
//复选框被选择触发函数
const handleSelectionChange = (rows) => {
    news.usersIds = rows;
}
const batchedDeleteByIds = async () => {
    //1.判断数组中是否包含删除元素
    if (news.usersIds.length <= 0) {
        ElMessage.warning("请选择删除项...")
        return; //结束
    }
    let ids = [];
    //2.遍历数组，获取所有id值
    for (let i = 0; i < news.usersIds.length; i++) {
        let u = news.usersIds[i];
        // console.log(u);
        //把值添加到数组中
        ids.push(u.newsid);
    }
    const idsStr = ids.toString();
    //3.发送异步请求
    let response = await request.delete(`/news/deleteByIds/${ids}`, { params: { idsStr } });
    if (response.data.success) {
        //显示提示信息
        ElMessage.success("批量删除成功")
        //刷新页面
        findAll(1);
    }
}
</script>